/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dyniablaster.logic;

import dyniablaster.graphics.*;

/**
 *
 * @author Damian2
 */


public class DyniaThread extends Thread
{
    boolean dyniaGameOver;
    private long lastRefreshTime;
    private long previousRefreshTime;
    int deltaTime;
    private long MIN_WAIT = 100;
    int SPEED;

    DyniaBlasterCanvas dyniaCanvas;
    DyniaBlasterVisualMIDlet dyniaMidletThread;

    public DyniaThread(DyniaBlasterCanvas canvas, DyniaBlasterVisualMIDlet midlet)
    {
        dyniaGameOver = false;
        dyniaCanvas = canvas;
        dyniaMidletThread = midlet;
        SPEED = 5;
    }

    public void run()
    {
        try {
         // first initialize the custom data
        dyniaCanvas.getManager().init();

        } catch(Exception e) {
        //myDungeon.errorMsg(e);
        }

        dyniaCanvas.getKeyStates();

    // the actual game begins
    // flush any keystrokes that occurred before the
    // game started:
    try
    {
      dyniaCanvas.start();
    }
    catch(Exception e) {
      //myDungeon.errorMsg(e);
    }

        deltaTime = 0;
        previousRefreshTime = System.currentTimeMillis();

         while(true)
         {
            if(dyniaCanvas.dyniaGameOver)
                break;

            lastRefreshTime = System.currentTimeMillis();
            deltaTime = (int) (lastRefreshTime - previousRefreshTime);
            previousRefreshTime = lastRefreshTime;
            //check keys
            dyniaCanvas.checkKeys();

            //update

            dyniaCanvas.updateGame(deltaTime);

           

            synchronized(this) //czekaj tyle zeby bylo nie wiecej niz 20 FPS
            {
                try
                {
                    wait(getWaitTime());
                }
                catch(Exception e) {}
            }

         }

    }

    private long getWaitTime()
    {
    long retVal = 1;
    long difference = System.currentTimeMillis() - lastRefreshTime;
    if(difference < MIN_WAIT) {
      retVal = MIN_WAIT - difference;
    }
    return(retVal);
  }

}
